package com.linyubing.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet{
    //根据url路径进行方法的分发
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取url
        String requestURI = req.getRequestURI();
        //获取最后一段路径
        int index = requestURI.lastIndexOf("/");
        //获取方法名
        String methodName = requestURI.substring(index + 1);
        //获取当前servlet的Class对象
        Class<? extends BaseServlet> clazz= this.getClass();
        //反射获取指定的方法
        Method method = null;
        try {
            method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //执行指定的方法
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }

    }
}
